<template>
	<div class="contents">
		<el-tabs v-model="active1">
			<el-tab-pane label="基本信息" name="first">
				<el-form :inline="true" label-width="80px">
					<el-form-item label="出库仓库">
						<el-select v-model="formData.warehouse_id" placeholder="选择仓库">
							<el-option v-for="(item, index) in opt1" :key="index" :label="item.name" :value="item.id">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="出库类型">
						<el-input v-model="formData.type" type="text" disabled></el-input>
					</el-form-item>
					<el-form-item label="制单人:">
						<span>{{ $store.state.user.username }}</span>
					</el-form-item>
				</el-form>
			</el-tab-pane>
		</el-tabs>
		<el-tabs v-model="active1">
			<el-tab-pane label="出库商品清单" name="first">
				<el-form :inline="true" label-width="80px">
					<el-form-item label="商品">
						<el-input placeholder="请选商品名/助记码/编码/别名/关键字" style="width: 215px;">
							<el-button slot="append" icon="el-icon-plus" @click="showpop"></el-button>
						</el-input>
					</el-form-item>
					<el-form-item label="数量">
						<el-input type="text"></el-input>
					</el-form-item>
					<el-form-item label="">
						<el-button type="primary" icon="el-icon-plus">添加</el-button>
					</el-form-item>
				</el-form>
			</el-tab-pane>
		</el-tabs>
		<el-dialog title="请选择商品" :close-on-click-modal="false" custom-class="modals" :show-close="false"
			:visible.sync="dialogGoods" width="85%">
			<el-row :gutter="5" type="flex" align="middle">
				<el-col :span="16">
					<el-cascader></el-cascader>
				</el-col>
				<el-col :span="15">
					<el-cascader></el-cascader>
				</el-col>
				<el-col>
					<el-input placeholder="请输入商品名称/编码进行搜索">
						<el-button slot="append" icon="el-icon-search"></el-button>
					</el-input>
				</el-col>
				<el-col :span="5">
					<el-checkbox>显示库存为"0"的商品</el-checkbox>
				</el-col>
				<el-col>
					<span style="color: #03ac54; margin-left: 10px;">
						小贴士：鼠标单击表格行即可直接选中或修改
					</span>
				</el-col>
			</el-row>
			<el-table ref="multipleTable" :data="goodsData.list" border style="width: 100%; margin-top: 10px;"
				@select="selectGoods" height="449px">
				<el-table-column type="selection" width="55" align="center"></el-table-column>
				<el-table-column label="商品图片" prop="goodsImages.path">
					<template slot-scope="scope">
						<el-image :src="scope.row.goodsImages.path" style="width: 50px; height: 50px;" />
					</template>
				</el-table-column>
				<el-table-column prop="name" label="名称编码" width="220">
					<template slot-scope="scope">
						<div>{{ scope.row.name }}</div>
						<div>{{ scope.row.code }}</div>
					</template>
				</el-table-column>
				<el-table-column prop="goodsPrice.unit" label="单位"></el-table-column>
				<el-table-column prop="category.name" label="商品分类"></el-table-column>
				<el-table-column prop="warename" label="仓库"></el-table-column>
				<el-table-column prop="goodsPrice.price" label="价格"></el-table-column>
				<el-table-column prop="goodsPrice.stock" label="库存"></el-table-column>
				<el-table-column prop="qty" label="数量">
					<template slot-scope="scope">
						<el-input v-model="scope.row.qty"></el-input>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination background layout="total, prev, pager, next,sizes, jumper" :page-size="goodsData.pageSize"
				:page-sizes="[10, 20, 30, 40]" style="text-align: left;" :total="goodsData.total"
				@current-change="checkPage" />
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogGoods = false">取 消</el-button>
				<el-button type="primary" @click="handleSelect">
					确 认
				</el-button>
			</span>
		</el-dialog>
		<el-table :data="tableData" border style="width: 100%;">
			<el-table-column type="index" width="50" label="序号"></el-table-column>
			<el-table-column label="商品" width="180">
				<template slot-scope="scope">
					<div>{{ scope.row.name }}</div>
					<div style="color: rgb(153, 153, 153);">{{ scope.row.code }}</div>
				</template>
			</el-table-column>
			<el-table-column prop="detail" label="描述"></el-table-column>
			<el-table-column prop="unit" label="单位"></el-table-column>
			<el-table-column label="出库数量">
				<template slot-scope="scope">
					<el-input v-model="scope.row.qty"></el-input>
				</template>
			</el-table-column>
			<el-table-column prop="goodsPrice.price" label="单价">
				<template slot-scope="scope">
					<el-input v-model="scope.row.goodsPrice.price"></el-input>
				</template>
			</el-table-column>
			<el-table-column prop="address" label="金额(元)">
				<template slot-scope="scope">
					{{ scope.row.qty * scope.row.goodsPrice.price }}
				</template>
			</el-table-column>
			<el-table-column prop="address" label="库区库位"></el-table-column>
			<el-table-column prop="remarks" label="备注">
				<template slot-scope="scope">
					<el-input v-model="scope.row.remarks"></el-input>
				</template>
			</el-table-column>
			<el-table-column prop="address" label="操作">
				<template slot-scope="scope">
					<el-button size="mini" type="text" @click="handleDel(scope.$index,scope.row)">
						删除
					</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div class="sumTotal">
			合计:
			<span class="totalNum">{{ totalPrice }}</span>
		</div>
		<div class="remarks">
			<span class="labels">备注:</span>
			<span style="width: 100%;">
				<el-input v-model="formData.remarks" placeholder="请输入备注信息，长度 < 100"></el-input>
			</span>
		</div>
		<el-button @click="savefunc">保存</el-button>
		<el-button @click="goBack">取消</el-button>
	</div>
</template>

<script>
	import {
		getGoodsQuery
	} from '@/api/goodslist'


	import {
		getWarehouseQuery,
		WarehouseOutAdd,
    Warehouseentryedit,
		WarehouseinputQueryInfolist
	} from '@/api/warehouse'
	import {
		handleActivePath
	} from '@/utils/routes'
	import {
		mapActions
	} from 'vuex'
	export default {
		data() {
			return {
				active1: 'first',
				tableData: [],
        delList:[],
				opt1: [],
				formData: {
					warehouse_id: 1,
					type: '其他出库',
					remarks: '',
				},
        createdgoodslist:'', //商品初始化id
				dialogGoods: false,
				goodsData: [], //商品所有信息
				dataFilter: {
					pagesize: 10,
					current: 1,
				},
				selectData: [],
			}
		},
		computed: {
			totalPrice() {
				let finalPrice = 0
        if(this.tableData.length != 0){
          for (let book of this.tableData) {
          	finalPrice += book.qty * book.goodsPrice.price
          }
				return finalPrice
        }else{
          return 0
        }
			},
		},
		async created() {
			if (this.$route.params.id) {
				let data = {
					id: this.$route.params.id
				}
				let res = await WarehouseinputQueryInfolist(data)
        this.createdgoodslist = res.data
				this.formData.warehouse_id = res.data.warehouseId
				// this.tableData = res.data.list
				res.data.warehouseOutItemsList.forEach(async (item) => {
					let id = {
						id: item.productId
					}
					let shoppimg = await getGoodsQuery(id)
					shoppimg.data.list[0].qty = item.qty
					shoppimg.data.list[0].goodsPrice.price = item.price / 100
					this.tableData.push(shoppimg.data.list[0])
				})
			} else {}
			this.getList()
			let res = await getWarehouseQuery({})
			this.opt1 = res.data.list

		},
		methods: {
			showpop() {
				this.dialogGoods = true
				setTimeout( ()=>{
					this.getOpen()
				},1000)
			},
			getOpen() {
				this.tableData.forEach((e, index) => {
					this.goodsData.list.forEach((i, w) => {
						if (i.id == e.id) {
							this.$refs.multipleTable.toggleRowSelection(this.goodsData.list[w], true);
						}
					})
				})
				this.$forceUpdate()
			},
			...mapActions({
				delVisitedRoute: 'tabs/delVisitedRoute',
			}),
			async getList() {
				const res = await getGoodsQuery(this.dataFilter)

				this.goodsData = res.data
				let list = []
				this.tableData.forEach((aaa) => {
					this.goodsData.list.forEach((item) => {
						if (aaa.id == item.id) {
							list.push(item)
						}
					})
				})
				this.selectData = list
				console.log("selectData", this.selectData);
			},
			checkPage(page) {
				this.dataFilter.current = page
				this.getList()
				this.getOpen()
			},
			selectGoods(sel, row) {
				console.log("sel", sel);
				this.selectData = sel
			},
			handleSelect() {
				if (this.selectData.length !== 0) {
					this.tableData = this.selectData
					this.dialogGoods = false
				} else {
					this.$confirm('请选择需要添加的商品', '操作失败', {
						showClose: false,
						showCancelButton: false,
						closeOnClickModal: false,
						confirmButtonText: '确定',
						type: 'error',
					})
				}
			},
			handleDel(index, item) {
				this.tableData.splice(index, 1)
				console.log(item, '11111')
        this.createdgoodslist.warehouseOutItemsList.forEach((itemres)=>{
          if(itemres.productId == item.id){
            this.delList.push(itemres.id)
          }
        })
				this.$refs.multipleTable.toggleRowSelection(item);
			},
			async goBack() {
				const detailPath = await handleActivePath(this.$route, true)
				await this.$router.push('/roomstore/deliveryManage')
				await this.delVisitedRoute(detailPath)
			},
			async savefunc() {
if (this.$route.params.id){
  console.log("删除",this.delList);
    let warehouseInputItemsList = []
  console.log(this.createdgoodslist);
  console.log(this.tableData);
  this.tableData.forEach((item)=>{
      let warlist = {
        no:this.createdgoodslist.no,
        inputId:this.$route.params.id,
        warehouseAreaId:item.area_id,
        warehouseSpaceId:item.space_id,
        productId:item.id,
        qty:item.qty,
        unit:item.unit,
        price:parseInt(item.goodsPrice.price*100)
      }
      warehouseInputItemsList.push(warlist)
  })
  let data ={
    id:this.$route.params.id,
    total:parseInt(this.totalPrice*100),
    status:0,
    delList:this.delList,
    warehouseOutItemsList:warehouseInputItemsList
  }
  console.log(data,2222222222222222222);

  let awaitres = await Warehouseentryedit(data)
  if(awaitres.status == 200){
    this.$message.success("修改成功")
    this.goBack()
  }else{
    this.$message.error("修改失败")
  }

  console.log(awaitres);
  // warehouseInputItemsList
}else{
  let WarehouseInputItemsList = []
  this.tableData.forEach((item) => {
  	let data = {
  		warehouseSpaceId: item.space_id, //库位id
  		warehouseAreaId: item.area_id, //库区id
  		productId: item.id,
  		qty: item.qty,
  		unit: item.unit,
  		price: Math.floor(item.goodsPrice.price * 100),
  		cuser: item.cuser,
  		uuser: item.uuser,
  	}
  	WarehouseInputItemsList.push(data)
  })
  let data = {
  	warehouseId: this.formData.warehouse_id,
  	total: this.totalPrice,
  	status: 0,
  	cuser: this.$store.state.user.username,
  	uuser: this.$store.state.user.username,
  	type: this.formData.type,
  	remarks: this.formData.remarks,
  	warehouseOutItemsList: WarehouseInputItemsList
  }
  // alert("保存")WarehouseOutAdd
  let s = await WarehouseOutAdd(data)
  console.log(s);
  if (s.status == 200) {
  	this.$message({
  		message: "添加成功",
  		type: "success"
  	})
  	this.goBack()
  } else {
  	this.$message({
  		message: "添加失败",
  		type: "error"
  	})
  }
}

			}
		},
	}
</script>

<style lang="scss" scoped>
	.contents {
		padding: 0 20px 10px;

		.sumTotal {
			border: 1px solid #f0f2f0;
			border-top: none;
			padding: 15px;
			text-align: right;

			.totalNum {
				font-size: 16px;
				color: #e20000;
			}
		}

		.remarks {
			display: flex;
			align-items: center;
			padding: 30px 0;

			.labels {
				margin-right: 15px;
				width: 35px;
			}
		}
	}
</style>
